/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact z_huatai@qq.com
 *  
 */
package org.zfes.snowy.base.web.json;


import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;

import com.alibaba.fastjson.serializer.ValueFilter;

/**
 * byte[] Fastjson 会直接 base64 给前端，此处做过滤
 * @author zhaohuatai
 *
 */
public class FastJsonByteArrayTextFilter implements ValueFilter{

	private Set<String> cachedFiled=new HashSet<String>();
	@Override
	public Object process(Object object, String propertyName, Object propertyValue) { 
		if(propertyValue==null){return "";}
		
		if(cachedFiled.contains(object.getClass().getName()+propertyName)){
			return new String((byte[])propertyValue);
		}
		
		if(propertyValue instanceof byte[]){
			byte[] content=(byte[] )propertyValue;
			Field[] fields=object.getClass().getDeclaredFields();
			Optional<Field> fieldx=Stream.of(fields)
			.filter(field-> field.isAnnotationPresent(LongTextJsonField.class)&&field.getName().equals(propertyName)).findAny();
			if(fieldx.isPresent()){
				String fullFieldName=object.getClass().getName()+fieldx.get().getName();
				if(cachedFiled.size()<1200){
					cachedFiled.add(fullFieldName);
				}
				return new String(content);
			}
		}
		return propertyValue;
	}

}
